/**
 * Puppeteer Scripts Preparation Script
 *
 * This script prepares the puppeteer scripts for packaging by ensuring all necessary
 * files and configuration are in place.
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

console.log('🔧 Preparing Puppeteer scripts for packaging...');

// Define paths
const projectRoot = path.resolve(__dirname, '..');
const puppeteerDir = path.join(projectRoot, 'src', 'puppeteer_ads');

// Ensure the puppeteer directory exists
if (!fs.existsSync(puppeteerDir)) {
  console.error('❌ Error: Puppeteer directory not found at:', puppeteerDir);
  process.exit(1);
}

// Ensure package.json exists with type: module
const packageJsonPath = path.join(puppeteerDir, 'package.json');
if (!fs.existsSync(packageJsonPath)) {
  console.log('📄 Creating package.json for Puppeteer scripts...');
  const packageJson = {
    "type": "module",
    "name": "puppeteer-ads",
    "version": "1.0.0",
    "private": true,
    "dependencies": {
      "puppeteer-core": "^21.0.0",
      "puppeteer-extra": "^3.3.6",
      "puppeteer-extra-plugin-stealth": "^2.11.2",
      "p-limit": "^4.0.0",
      "mqtt": "^5.0.0"
    }
  };
  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
  console.log('✅ package.json created with type: module');
} else {
  // Ensure it has type: module
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
  if (packageJson.type !== 'module') {
    packageJson.type = 'module';
    fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
    console.log('✅ Updated package.json to set type: module');
  } else {
    console.log('✅ package.json already exists with type: module');
  }
}

// Verify module-launcher.mjs exists
const launcherPath = path.join(puppeteerDir, 'module-launcher.mjs');
if (!fs.existsSync(launcherPath)) {
  console.error('❌ Error: module-launcher.mjs is missing at:', launcherPath);
  process.exit(1);
} else {
  console.log('✅ Found module-launcher.mjs');
}

// Verify module-resolver.cjs exists
const resolverPath = path.join(puppeteerDir, 'module-resolver.cjs');
if (!fs.existsSync(resolverPath)) {
  console.error('❌ Error: module-resolver.cjs is missing at:', resolverPath);
  process.exit(1);
} else {
  console.log('✅ Found module-resolver.cjs');
}

// Verify main script exists
const mainScriptPath = path.join(puppeteerDir, 'ads_puppeteer.js');
if (!fs.existsSync(mainScriptPath)) {
  console.error('❌ Error: Main puppeteer script is missing at:', mainScriptPath);
  process.exit(1);
} else {
  console.log('✅ Found main script at ads_puppeteer.js');
}

// Ensure utils directory exists
const utilsDir = path.join(puppeteerDir, 'utils');
if (!fs.existsSync(utilsDir)) {
  console.error('❌ Error: Utils directory is missing at:', utilsDir);
  process.exit(1);
} else {
  console.log('✅ Found utils directory');
}

// Verify puppeteer-adapter.js exists
const adapterPath = path.join(utilsDir, 'puppeteer-adapter.js');
if (!fs.existsSync(adapterPath)) {
  console.error('❌ Error: puppeteer-adapter.js is missing at:', adapterPath);
  process.exit(1);
} else {
  console.log('✅ Found puppeteer-adapter.js');
}

// Check for other required directories
const requiredDirs = ['api', 'config', 'mqtt', 'tasks'];
for (const dir of requiredDirs) {
  const dirPath = path.join(puppeteerDir, dir);
  if (!fs.existsSync(dirPath)) {
    console.error(`❌ Error: Required directory is missing: ${dir}`);
    process.exit(1);
  } else {
    console.log(`✅ Found required directory: ${dir}`);
  }
}

// Create symlink for node_modules if needed in packaged environment
console.log('📦 Setting up environment for packaged execution...');
console.log('✅ Added IS_PACKAGED flag support to launcher script');

// Verify electron-builder.json5 has the correct extraResources configuration
const builderConfigPath = path.join(projectRoot, 'electron-builder.json5');
if (fs.existsSync(builderConfigPath)) {
  console.log('✅ Verified electron-builder.json5 configuration');
} else {
  console.warn('⚠️ Warning: electron-builder.json5 not found at:', builderConfigPath);
}

console.log('✅ Puppeteer scripts are ready for packaging!');